import axios from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/user";
import router from "@/router";
const request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 5000,
});
request.interceptors.request.use((config) => {
    if (!config.headers.Authorization && useUserStore().token) {
        config.headers.Authorization = useUserStore().userToken
    }
    return config;
});
request.interceptors.response.use(config => {
    if (config.status == 200 && config.data.code == 200) return config.data;
    ElMessage.error(config.data.msg);
    return Promise.reject(new Error(config.data.msg));
}, error => {
    let message = "";
    let status = error.response.status;
    switch (status) {
        case 401:
            message = "TOKEN过期,请重新登录";
            useUserStore().clearToken()
            router.push("/login")
            break;
        case 403:
            message = "无权访问";
            break;
        case 404:
            message = "请求地址错误";
            break;
        case 500:
            message = "服务器出现问题";
            break;
        default:
            message = error.response.data.msg;
    }
    ElMessage({
        type: "error",
        message,
    });
    return Promise.reject(error);
}
);

export enum Controller {
    friendship = "/friendship",
    group = "/chatroom",
    user = "/user",
    history = "/chat-history"
}
export default request;
